from DataAccess.DBConnFactory import DBConnFactory
from Import.TradeImport import *
from Position.CalcDailyPosition import *
from Mark2Mkt.CalcMktValue import *
from Accounting.Routine.Settle import *
from Accounting.Routine.OpenDayOp import settle_sub_red_operations
from check_privilege import *

from datetime import date, timedelta

def run(ref_date):
	print 'info, Routine@',	ref_date.isoformat(), ', Step 0: Clearing records>=', ref_date.isoformat(), '...'
	clear_records_no_later_than(ref_date)
	
	print 'info, Routine@',	ref_date.isoformat(), ', Step 1: Import trades starting...'
	#import_daily_trades(ref_date)
	print 'info, Routine@',	ref_date.isoformat(), ', Step 1: Import trades completed.'
	
	print 'info, Routine@',	ref_date.isoformat(), ', Step 2: Update dividend starting...'
	update_position_driven_by_dividend(ref_date)
	print 'info, Routine@',	ref_date.isoformat(), ', Step 2: Update dividend completed.'

	print 'info, Routine@',	ref_date.isoformat(), ', Step 3: Update position by transaction starting...'	
	update_position_driven_by_transaction(ref_date)
	print 'info, Routine@',	ref_date.isoformat(), ', Step 3: Update position by transaction completed.'

	print 'info, Routine@',	ref_date.isoformat(), ', Step 4: Update position by repo expire starting...'	
	update_position_driven_by_repo_expire(ref_date)	
	print 'info, Routine@',	ref_date.isoformat(), ', Step 4: Update position by repo expire completed.'
	
	update_daily_position(ref_date)	
	
	print 'info, Routine@',	ref_date.isoformat(), ', Step 5: Update security price starting...'	
	#update_security_to_latest_price(ref_date)
	print 'info, Routine@',	ref_date.isoformat(), ', Step 5: Update security price completed.'

	print 'info, Routine@',	ref_date.isoformat(), ', Step 6: Mark portfolio to market starting...'		
	calc_portf_mkt_val(ref_date)	
	print 'info, Routine@',	ref_date.isoformat(), ', Step 6: Mark portfolio to market completed.'

	print 'info, Routine@',	ref_date.isoformat(), ', Step 7: Settle fees starting...'
	settle_fees(ref_date)
	print 'info, Routine@',	ref_date.isoformat(), ', Step 7: Settle fees completed.'
	
	print 'info, Routine@',	ref_date.isoformat(), ', Step 8: Settle Sub/Red operations starting...'
	settle_sub_red_operations(ref_date)
	print 'info, Routine@',	ref_date.isoformat(), ', Step 8: Settle Sub/Red operations completed.'
	
	print 'info, Routine@',	ref_date.isoformat(), ', Step 8: Update portfolio cash position starting...'
	reflect_to_portf_cash_account(ref_date)
	calc_portf_mkt_val(ref_date, True)
	print 'info, Routine@',	ref_date.isoformat(), ', Step 8: Settle portfolio cash position completed.'
	
	print 'info, Routine@',	ref_date.isoformat(), ', All jobs completed.'
	print '-------------------------------------------------------------'
	

def run2(start_date):
	d = start_date
	one_day = timedelta(days=1)
	while d<=date.today():
		#if d.weekday()!=5 and d.weekday()!=6:
		#	run(d)
		run(d)
		
		d += one_day
		

		
def clear_records_no_later_than(ref_date):
	conn = DBConnFactory().get_db_connection('ACCOUNTING')
	
	str_date = ref_date.isoformat()	
	conn.cursor().execute("delete from asset_value where official='F' and ref_date>=TO_DATE('"+str_date+"','yyyy-mm-dd')")
	conn.cursor().execute("delete from fee where official='F' and ref_date>=TO_DATE('"+str_date+"','yyyy-mm-dd')")
	conn.cursor().execute("delete from cash_chg where ref_date>=TO_DATE('"+str_date+"','yyyy-mm-dd')")	
	conn.cursor().execute("delete from share_chg where ref_date>=TO_DATE('"+str_date+"','yyyy-mm-dd')")
	conn.commit()
	
	pke_conn = DBConnFactory().get_db_connection('PKEDB')
	pke_conn.cursor().execute("delete from portfolio_mkt_val where ref_date>=TO_DATE('"+str_date+"','yyyy-mm-dd')")
	pke_conn.cursor().execute("delete from cash_switch where ref_date>=TO_DATE('"+str_date+"','yyyy-mm-dd')")
	pke_conn.cursor().execute("delete from cash_dividend_flow where event_date>=TO_DATE('"+str_date+"','yyyy-mm-dd')")
	pke_conn.cursor().execute("delete from stock_dividend_flow where event_date>=TO_DATE('"+str_date+"','yyyy-mm-dd')")
	pke_conn.cursor().execute("delete from position where ref_date>=TO_DATE('"+str_date+"','yyyy-mm-dd')")
	pke_conn.commit()
	

	
def check_prerequisite(ref_date):
	print 'info, Routine@', ref_date.isoformat(), ' Check prerequisite starting...'

	conn = DBConnFactory().get_db_connection('ACCOUNTING')
	cursor = conn.cursor()
	cursor.execute('''select id,max(ref_date) latest_shdl
				from fee_schedule
				group by id''')
	all_is_ok = True
	for item in cursor.fetchall():
		if item[1].date()<ref_date:
			print "    warn, Schedule ", item[0], " REQUIRE UPDATE!"
			all_is_ok = False
			
	if all_is_ok:
		print 'info, Routine@', ref_date.isoformat(), ' Check prerequisite completed.\n'
	#print
		
		
			
if __name__ == '__main__':
	print "Please Login..."
	#if not check_usr_privilege():
	#	print 'Wrong User or Password.'
	#	exit(0)

	date_str = raw_input('operation date(yyyymmdd): ')
	if len(date_str)!=8:
		print 'ERROR: NOT Required Date Format.'	
		exit(0)
		
	op_date = datetime.strptime(date_str, '%Y%m%d').date()
	
	#check_prerequisite(ref_date)
	if op_date==date.today():
		run(op_date)
	else:
		run2(op_date)
	
	